package com.genewoo.jta.plugin;

import java.lang.reflect.Array;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.HashMap;

import de.mud.jta.Main;
import de.mud.jta.Repository;

public class Util {
	
	public final static HashMap<String, String> FUNC_KEYS = new HashMap<String,String>();
	
	static {
		FUNC_KEYS.put("F1", "\u001b[11~");
		FUNC_KEYS.put("F2", "\u001b[12~");
		FUNC_KEYS.put("F3", "\u001b[13~");
		FUNC_KEYS.put("F4", "\u001b[14~");
		FUNC_KEYS.put("F5", "\u001b[15~");
		FUNC_KEYS.put("F6", "\u001b[17~");
		FUNC_KEYS.put("F7", "\u001b[18~");
		FUNC_KEYS.put("F8", "\u001b[19~");
		FUNC_KEYS.put("F9", "\u001b[20~");
		FUNC_KEYS.put("F10", "\u001b[21~");
		FUNC_KEYS.put("F11", "\u001b[22~");
		FUNC_KEYS.put("F12", "\u001b[23~");
		
		FUNC_KEYS.put("ESC", "\u001b");
		FUNC_KEYS.put("CTRL-C", "\u0003");
		FUNC_KEYS.put("BACKSAPCE", "\b");
		
		FUNC_KEYS.put("UP", "\u001b[A");
		FUNC_KEYS.put("DOWN", "\u001b[B");
		FUNC_KEYS.put("LEFT", "\u001b[D");
		FUNC_KEYS.put("RIGHT", "\u001b[C");
		
		FUNC_KEYS.put("RETURN", "\u001b[C");	
		
	}
	
    public static byte[] getBytes(String input) {
        byte arr[] = new byte[input.length()];
        for (int i = 0; i < input.length(); i++) {
        	arr[i] = (byte) input.charAt(i);
        	//System.out.println(arr[i]);
        }
        return arr;
    }
    
    public static void sleep(long time) {
    	long start = System.currentTimeMillis();
    	while(start + time > System.currentTimeMillis()) {
    		Thread.yield();
    	}
    }
    
    public static char[][] getScreen() {
    	return Repository.buffer.charArray;
    }
    
    public static String getText(int xstart, int ystart, int length) {
    	char[] result = new char[length];
    	int ybase = Repository.buffer.charArray.length - 24;
    	int j = 0;
    	for (int i = xstart - 1; i < xstart + length - 1; i++) {
			result[j] = Repository.buffer.charArray[ybase + ystart - 1][i];
			j++;			
		}
    	return String.valueOf(result);
    }
    

    /**
     * Support F1 to F12.
     * @param key
     */
    public static byte[] funKey(String key) {
    	byte[] ba = new byte[0];
    	if (FUNC_KEYS.containsKey(key)){
    		ba = getBytes(FUNC_KEYS.get(key));
    	}
    	return ba;
    }
}
